package org.noote.libs.skeleton;

import java.util.ArrayList;

import org.noote.libs.sogle.Vector3D;
import org.noote.libs.sogle.Quaternion;

import android.opengl.Matrix;

public class Bone {

	private float _matrixLocal[] = new float[16];
	private float _matrixGlobal[] = new float[16];
	
	protected Quaternion _quat = new Quaternion();
	protected Vector3D _offset = new Vector3D();
	protected float _length;
	
	protected Bone _parent = null;
	protected ArrayList<Bone> _childs = new ArrayList<Bone>();
	
	public Bone()
	{
		Matrix.setIdentityM(getLocalMatrix(), 0);
		Matrix.setIdentityM(getGlobalMatrix(), 0);
	}
	
	public void set(Vector3D offset, float length)
	{
		_offset = offset;
		_length = length;
	}

	public void setParent(Bone parent) {
		_parent = parent;
		_parent.addChild(this);
	}

	public void addChild(Bone bone) {
		_childs.add(bone);
	}

	public Quaternion getQuaternion() {
		return _quat;
	}

	public void setQuaternion(Quaternion quat) {
		this._quat = quat;
	}

	public float[] getLocalMatrix() {
		return _matrixLocal;
	}
	public float[] getGlobalMatrix() {
		return _matrixGlobal;
	}
	
	public void update(float inMatrix[])
	{
		float offsetmat[] = new float[16];
		float quatmat[] = new float[16];
		_quat.toMatrix_4x4(quatmat);
		
		Matrix.translateM(offsetmat, 0, inMatrix, 0, _offset.x, _offset.y, _offset.z);
		Matrix.multiplyMM(_matrixLocal, 0, offsetmat, 0, quatmat, 0);
		
		float tmat[] = new float[16];
		// TODO ? Matrix.translateM(tmat, 0, _matrix, 0, _length, 0, 0);
		Matrix.translateM(tmat, 0, _matrixLocal, 0, 0, 0, 0);
		
		for(Bone child : _childs)
		{
			child.update(tmat);
		}
	}
}
